<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js" type="text/javascript"></script>

  <style>
    .item-container {
      display: flex;
      justify-content: space-around;
      background-color: pink;
      height: 30px;
    }

    .right-container {
      display: flex;
    }

  </style>
</head>


<body>
  <div id="root">
    <div v-for="(item,index) in list" class="item-container">
      <div>{{item.name}}</div>
      <div class="right-container">

        <div>
          {{item.price | currencyUSD}}
        </div>

        <div>
          <button @click="sub(index)">-</button>
          {{item.count}}
          <button @click="add(index)">+</button>
        </div>

      </div>
    </div>

    <div>{{total | currencyUSD}}</div>

  </div>
  <script>
    //   自定义过滤器(全局)
    Vue.filter('currencyUSD', function (value) {
      return '￥' + value
    })
    let vm = new Vue({
      el: "#root",
      data: function () {
        return {
          list: [{
              name: '黄瓜',
              price: 3,
              count: 1
            },
            {
              name: '苹果',
              price: 5,
              count: 1
            },
            {
              name: '西瓜',
              price: 6,
              count: 1
            },
            {
              name: '阳光玫瑰',
              price: 10,
              count: 1
            }
          ]
        }
      },
      methods: {
        sub(index) {
          if (this.list[index].count > 1) {
            this.list[index].count--;
          } else {
            alert('至少购买1份哦！')
          }
        },
        add(index) {
          if (this.list[index].count < 10) {
            this.list[index].count++;
          } else {
            alert('限购四10份哦！')
          }
        }
      },
      computed: {
        total() {
          let sum = 0;
          this.list.forEach((item) => {
            sum += item.price * item.count
          })
          return sum;
        }
      }
    })

  </script>

</body>

</html>
